package com.smartlazy.delay.queue.core.service;

import com.smartlazy.delay.queue.core.constant.CommonConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author howe
 */
@Slf4j
@Service
public class ReadyQueue implements Serializable {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 添加JobId到队列中
     * @param topic
     * @param jobId
     * @return
     */
    public long pushToReadyQueue(String topic, String jobId) {
        String key = CommonConst.DEFAULT_QUEUE_KEY + topic;
        ListOperations<String, String> list = redisTemplate.opsForList();
        return list.rightPush(key, jobId);
    }

    /**
     * 从队列中阻塞获取JobId
     * @param queues
     * @param timeout
     * @return
     */
    public String blockPopFromReadyQueue(String queues, int timeout) {
        String key = CommonConst.DEFAULT_QUEUE_KEY + queues;
        BoundListOperations<String, String> list = redisTemplate.boundListOps(key);
        return list.leftPop(timeout, TimeUnit.SECONDS);
    }
}
